using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Pavilion
{
    public abstract class NodeBase
    {
        public event NameChangedDelegate NameChanged;

        public List<GameData> GameDataCollection { get { return (_gameDataCollection == null) ? _gameDataCollection = new List<GameData>() : _gameDataCollection; } }
        public ContainerNode ParentContainer { get; set; }
        public string Name { get { return _name; } set { SetName(value); } }
        public IEnumerable<Link> BoundLinks { get { return boundLinks; } }
        public string GameItemName { get; set; }

        private string _name;
        private List<GameData> _gameDataCollection;
        private List<Link> boundLinks;

        public NodeBase()
        {
            boundLinks = new List<Link>();
        }

        public virtual void Dispose()
        {
            ParentContainer = null;
        }

        public abstract NodeBase Clone();

        protected void InsertParentContent(NodeBase nodeBase)
        {
            foreach (var gameData in this.GameDataCollection)
                nodeBase.GameDataCollection.Add(gameData.Clone());
        }

        internal Link GetLink(int index)
        {
            return boundLinks[index];
        }

        internal void BindLink(Link link)
        {
            boundLinks.Add(link);
        }

        internal void UnbindLink(Link link)
        {
            boundLinks.Remove(link);
        }

        internal virtual void UpdateGameToolData(GameItem gameItem)
        {
            if (_gameDataCollection == null)
                return;

            if (!string.IsNullOrEmpty(GameItemName))
                gameItem = GameItemManager.Instance[GameItemName];

            foreach (GameData gameData in GameDataCollection)
                gameData.UpdateGameData(gameItem);
        }

        public override string ToString()
        {
            return Name;
        }

        private void SetName(string value)
        {
            if (_name == value)
                return;

            string oldName = _name;
            _name = value;
            OnNameChanged(oldName, _name);
        }

        private void OnNameChanged(string oldName, string newName)
        {
            if (NameChanged != null)
                NameChanged(oldName, newName);
        }
    }
}
